package com.heima.home.service.impl;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.heima.home.dto.PageResponse;
import com.heima.home.entity.Properties;
import com.heima.home.exception.CustomException;
import com.heima.home.mapper.PropertyMapper;
import com.heima.home.service.PropertyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class PropertyServiceImpl implements PropertyService {

    @Autowired
    private PropertyMapper propertyMapper;

    @Override
    public PageResponse<Properties> getPropertyList(int pageNum, int pageSize) {
        // 1. 设置分页参数: 只有紧跟在它后面的第一个MyBatis查询会被分页
        PageHelper.startPage(pageNum, pageSize, "is_hot DESC, created_at DESC");

        // 2. 执行查询
        List<Properties> properties = propertyMapper.findAllActive();

        // 3. 用 PageInfo 包装查询结果，它包含了分页的所有信息
        PageInfo<Properties> pageInfo = new PageInfo<>(properties);

        System.out.println("PageHelper 分页信息: ");
        System.out.println(" - 总记录数 (Total): " + pageInfo.getTotal());
        System.out.println(" - 当前页数据量 (Size): " + pageInfo.getSize());
        System.out.println(" - 总页数 (Pages): " + pageInfo.getPages());

        // 4. 转换为我们自定义的 PageResponse DTO
        PageResponse<Properties> response = new PageResponse<>();
        response.setTotal(pageInfo.getTotal());
        response.setPageNum(pageInfo.getPageNum());
        response.setPageSize(pageInfo.getPageSize());
        response.setList(pageInfo.getList());

        return response;
    }
    
    @Override
    public Properties getPropertyById(Long id) {
        if (id == null || id <= 0) {
            throw new CustomException("房源ID不合法");
        }
        
        try {
            Properties property = propertyMapper.selectById(id);
            if (property == null) {
                log.warn("房源不存在: id={}", id);
                throw new CustomException("房源不存在");
            }
            return property;
        } catch (CustomException e) {
            throw e;
        } catch (Exception e) {
            log.error("查询房源异常: id={}", id, e);
            throw new CustomException("查询房源失败");
        }
    }

}